package com.coffee.log.capture;
import org.springframework.context.expression.MethodBasedEvaluationContext;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * @author songkui
 * @since 2025/4/25
 */
@Component
public class CoffeeSpELParser {

    private final ExpressionParser parser = new SpelExpressionParser();

    private final DefaultParameterNameDiscoverer nameDiscoverer = new DefaultParameterNameDiscoverer();

    public String parse(String spEL, Method method, Object[] args, Object result, String errorMsg) {
        try {
            // 1. 创建评估上下文
            StandardEvaluationContext context = new MethodBasedEvaluationContext(
                    null, method, args, nameDiscoverer
            );

            // 2. 注入额外变量
            context.setVariable("result", result);
            context.setVariable("errorMsg", errorMsg);

            // 3. 解析表达式
            Expression expression = parser.parseExpression(spEL);
            return Optional.ofNullable(expression.getValue(context))
                    .map(Object::toString)
                    .orElse("");
        } catch (Exception e) {
            // 解析失败时返回原始表达式（或自定义错误信息）
            return spEL + "[PARSE_ERROR]";
        }
    }
}
